package com.hksj.common.quartz.base;

import com.hksj.common.config.utils.SpringContextUtil;
import com.hksj.common.quartz.entity.CronJobLog;
import com.hksj.common.quartz.service.CronJobLogService;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;

public abstract class BaseJob implements Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        CronJobLog cronJobLog = new CronJobLog();
        CronJobLogService cronJobLogService = (CronJobLogService)SpringContextUtil.getBean("cronJobLogService");
        try{
            JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
            long jobId = jobDataMap.getLong("jobId");
            String cron = jobDataMap.getString("cron");
            cronJobLog.setJobId(jobId);
            cronJobLog.setCron(cron);
            cronJobLog.setStartTime(new Date());
            exec(jobDataMap);
            cronJobLog.setStatus(1);
        }catch (Exception e){
            cronJobLog.setStatus(0);
            cronJobLog.setRemark(e.getMessage());
        }finally {
            cronJobLog.setEndTime(new Date());
            cronJobLogService.save(cronJobLog);
        }
    }

    public abstract void exec(JobDataMap jobDataMap);
}
